package FileHandling;

import Map.Mindmap;
import java.io.IOException;
import javax.microedition.rms.*;

/**
 * Saves and loads mindmaps from the RMS.
 *
 * @author Lewis Marhin and John Gray-Spence
 */
public class LocalStorage {

    private static RecordStore rs;

    /**
     * Destructor for LocalStorage class. Makes sure RMS is closed.
     */
    protected void finalize() {
        try {
            rs.closeRecordStore();
        } catch (RecordStoreNotOpenException ex) {
            ex.printStackTrace();
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Returns the record store where maps are stored.
     */
    private static RecordStore getRecordStore() {
        try {
            return RecordStore.openRecordStore("mapStorage", true, RecordStore.AUTHMODE_ANY, true);
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * Adds a map to the record store.
     *
     * @param m Mindmap object to be saved to RMS.
     * @throws javax.microedition.rms.RecordStoreException Thrown when RecordStore has issues.
     * @throws java.io.IOException Thrown when there is problem opening or writing to RMS fle.
     */
    public static void addMap(Mindmap m) throws RecordStoreException, IOException {
        rs = getRecordStore();
        byte[] byteMap = ByteConverter.mapToByteArray(m);
        rs.addRecord(byteMap, 0, byteMap.length);
    }

    /**
     * Loads a Mindmap object from the RMS.
     *
     * @return Mindmap for loading into UI.
     * @throws javax.microedition.rms.RecordStoreException Thrown when RecordStore has issues.
     * @throws java.io.IOException  Thrown whne there is problem opening or reading RMS file.
     */
    public static Mindmap readMap() throws RecordStoreException, IOException {
        rs = getRecordStore();
        Mindmap m = ByteConverter.byteArrayToMap(rs.getRecord(0));
        return m;
    }
}
